/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
/*
 * Created on 24 oct. 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package fr.jade.console.cmd;

import java.util.LinkedList;

import org.objectweb.fractal.api.Component;

import fr.jade.console.core.AbstractCommand;
import fr.jade.console.core.Command;
import fr.jade.console.core.Environment;
import fr.jade.fraclite.orb.registry.NamingService;
import fr.jade.fraclite.orb.registry.Registry;

/**
 * @author ssicard
 */
public class Connect extends AbstractCommand implements Command{

  public String getDescription(){
    return "connects a remote MiniJade";
  }
  
  public String getHelp(){
    return "connect <host> <port> <cmpName>";
  }
  
  public String getName() {
    return "connect";
  }
  
	public Object execute(String[] args, Environment env) throws Throwable {
	  
	  String opt = null;
    
    if(args.length == 1){
      opt = "-help";
    }else if(args[1].equals("-help")){
      opt = "-help";
    }else{
      opt = "";
    }
	  
    if(opt.equals("-help")){
      System.out.println("Usage : connect <host> <port> <cmpName>");
    }else{
  		System.out.println("connecting to registry on "+ args[1] + ":"+ args[2]);
  		try{
  		NamingService ns = Registry.getRegistry(args[1], Integer.parseInt(args[2]));
  		System.out.println("lookup("+args[3]+")");
  		
  		Component cmp = ns.lookup(args[3]);
  		env.setEnvVar("current", cmp);
  		
  		LinkedList<Component> ll = new LinkedList<Component>();
  		ll.addLast(cmp);
  		env.setEnvVar("pwd",ll);
  		
  		}catch(Exception e){
  			e.printStackTrace();
  		}
    }
		return null;
	}
}
